from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time
import openpyxl
import requests
import re
import json

# 等待整个table加载完成，否则因网络延迟，driver.page_source可能会拿不到数据
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

# wb = openpyxl.load_workbook(r"D:\tiktok.xlsx")
wb = openpyxl.Workbook()
ws = wb.create_sheet('自定义订单模板')
# sheet = wb.worksheets[0]
list1 = ['1']
list2 = ['1']
list3 = ['1']
chrome_options = Options()
# chrome_options.add_argument("--headless")
# chrome_options.add_argument("--no-sandbox")
# rizhi = chrome_options.add_argument('--log-level=3')
browser = webdriver.Chrome(options=chrome_options,
                           executable_path=r'C:\Program Files\Google\Chrome\Application\chromedriver.exe')

jim = """WEC0412111030251,WEC0822111030250,WEC0292111030249,WEC0952111030248,WEC0282111030247,WEC0692111030246,WEC0832111030245,WEC0212111030244,WEC0122111030240,WEC0482111030243"""
jim01 = jim.split(',')[::-1]


def oop3():
    # browser = webdriver.Chrome()
    browser.get('https://seller.tiktokglobalshop.com/account/login')
    # time.sleep(3)
    WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'TikTok_Ads_SSO_Login_Form')))
    browser.find_element_by_xpath(
        "//div[@id='TikTok_Ads_SSO_Login_Form']/div[@id='TikTok_Ads_SSO_Login_Form_Content']/div[@id='TikTok_Ads_SSO_Login_Mobile_FormItem']/span[@id='TikTok_Ads_SSO_Login_Email_Panel_Button']").click()

    time.sleep(3)
    #
    # # 输入账户密码
    browser.find_element_by_id('TikTok_Ads_SSO_Login_Email_Input').click()
    browser.find_element_by_id('TikTok_Ads_SSO_Login_Email_Input').send_keys('xiaoyueteng@outlook.com')
    browser.find_element_by_id('TikTok_Ads_SSO_Login_Pwd_Input').click()
    browser.find_element_by_id('TikTok_Ads_SSO_Login_Pwd_Input').send_keys('6Q?4g#a1')
    time.sleep(2)
    browser.find_element_by_id('TikTok_Ads_SSO_Login_Btn').send_keys(Keys.ENTER)

    time.sleep(6)

    browser.get('https://seller.tiktokglobalshop.com/order?subTab=awaiting_collection&tab=to_ship')
    time.sleep(6)
    browser.get('https://seller.tiktokglobalshop.com/order?subTab=awaiting_collection&tab=to_ship')
    time.sleep(6)
    while 1:
        WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, 'index__TBodyContainer--ScorV')))
        one_all = browser.find_elements_by_xpath(
            "//tbody[@class='index__TBodyContainer--ScorV']/tr[@class='index__TBodyRowHeader--1St6W']")
        two_all = browser.find_elements_by_xpath(
            "//div[@class='index__content--2rT_g font-regular text-base text-gray-1 break-all']")
        for one_i in range(len(one_all)):
            time1 = one_all[one_i].text[-19:]
            name1 = one_all[one_i].text[19:-19]
            number1 = one_all[one_i].text[:18]
            list1.append(time1)
            list2.append(number1)
            list3.append(name1)

        try:
            browser.find_element_by_xpath(
                "//div[@class='arco-spin i18n-ecom-spin']/div[@class='arco-spin-children']/div[@class='zep-pagination justify-end']/ul[@class='zep-pagination-list']/li[@class='zep-pagination-item zep-pagination-item-next']").click()
            time.sleep(6)
        except Exception as g:
            break

    oop4()


# 订单分类	参考号	币种	买家ID	仓库id	仓库运输方式	跟踪号	平台运输方式代码	付款时间	运费	平台手续费	paypal 交易号	销售sku	单价	数量	收件人名称	国家二字码	州或省	城市名称	地址第一行	电话
def oop4():
    for i in range(1, len(list1)):
        number11 = list2[i]
        time11 = list1[i].split(' ')[0].split('/')
        time22 = time11[2] + '/' + time11[1] + '/' + time11[0]
        name11 = list3[i].replace('\n', '')
        browser.get(f'https://seller.tiktokglobalshop.com/order/detail?order_no={number11}')
        time.sleep(6)
        WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'index__info--2ZlBl')))
        SellerSKU = browser.find_element_by_xpath(
            "//div[@class='index__info--2ZlBl']/div[@class='index__sku-id--3OdTf']").text
        num2 = browser.find_element_by_xpath(
            "//div[@class='index__container--3SeqM']/div[@class='index__content--PpRp3 bg-white']/div[@class='index__price--3KYvw']").text
        try:
            addr = browser.find_element_by_xpath(
                "//div[@class='index__leftContainer--3TLdq space-y-16']/div[@class='index__container--30FGM'][5]/div[@class='index__value--vChAg']").text
        except Exception as g:
            addr = browser.find_element_by_xpath(
                "//div[@class='index__leftContainer--3TLdq space-y-16']/div[@class='index__container--30FGM'][4]/div[@class='index__value--vChAg']").text

        num22 = num2.split(' ')
        num2_moneylei = num22[0]
        num2_number = num22[3]
        num2_money = num22[1]
        wuliu1 = browser.find_element_by_xpath(
            "//div[@class='index__card--3DoQW rounded']/div[4]/div[@class='index__priceKeyValue--Fc6U2 mb-12 flex justify-between'][3]/div[@class='font-regular text-base text-gray-2'][2]").text
        wuliu2 = wuliu1.split(' ')[1]
        title = browser.find_element_by_xpath(
            "//div[@class='index__container--3SeqM']/div[@class='index__content--PpRp3 bg-white']/div[@class='index__info--2ZlBl']/div[@class='index__content--2rT_g']").text
        SellerSKU1 = SellerSKU.replace('Seller SKU : ', '')

        browser.back()
        time.sleep(6)

        one = f'''
            "platform": "b2c",
            "orderType": "line",
            "warehouseId":"2",
            "shippingMethod":"SHANGF",
            "shippingMethodPlatform":"TikTok Global Shipping",
            "refNo": "{number11}",
            "userAccount": "tiktop_yueteng",
            "currency": "{num2_moneylei}",
            "buyerId": "{name11}",
            "buyerName": "{name11}"

            '''

        two = f'''
            "productSku": "{SellerSKU1}",
            "unitPrice": {float(num2_money)},
            "qty": {int(num2_number)},
            "productTitle": "{title}"

        '''
        three = '''{
            "name": "万色快递",
            "countryCode": "CN",
            "cityName": "东莞市",
            "line1": "碧湖大道16号安和创新科技园2栋13F"
        },
        '''
        four = f'''

        "customerServiceNote": "{addr}"

        '''

        data1 = f'''
        "actionType": "EDIT",
        "saleOrderCode":"{jim01[i - 1]}",
        "order": {one}
        "orderDetails": {two}
        "orderAddress": {three}
        "orderProperty": {four}

        '''
        data1 = str(data1)
        data = f'''<?xml version="1.0" encoding="UTF-8"?>
                <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
                  xmlns:ns1="http://www.example.org/Ec/">
                  <SOAP-ENV:Body>
                    <ns1:callService>
                      <paramsJson>
                      {
        data1
        }
                      </paramsJson>
                      <service>syncOrder</service>
                      <userName>jinhuaitao</userName>
                      <userPass>jht834719#</userPass>
                    </ns1:callService>
                  </SOAP-ENV:Body>
                </SOAP-ENV:Envelope>'''
        title2 = f'"productTitle": "{title}"' + '\n}],'
        buyerName2 = f'"buyerName": "{name11}"' + '\n},'
        addr2 = f'"customerServiceNote": "{addr}"' + '\n}'
        data2 = data.replace('<paramsJson>', '<paramsJson>{').replace('</paramsJson>', '}</paramsJson>').replace(
            '"order": ', '"order": {').replace('"orderDetails": ', '"orderDetails": [{').replace(
            f'"productTitle": "{title}"', f'{title2}').replace(f'"buyerName": "{name11}"', f'{buyerName2}').replace(
            '"orderProperty": ', '"orderProperty": {').replace(f'"customerServiceNote": "{addr}"', addr2)

        print(i, 'data2', data2)
        response = requests.post(url='http://sw-eb.eccang.com/default/svc-open/web-service-v2',
                                 data=data2.encode('utf-8')).content.decode('utf-8')
        # print(response)
        re_response = re.findall('<response>(.*?)</response>', response)[0]
        re_response_json = json.loads(re_response)
        print(i, re_response_json, type(re_response_json))

    browser.close()


if __name__ == '__main__':
    oop3()
#     oop4()
